package com.fingard.dsp.bank.directbank.gzelink01;

import com.fingard.dsp.bank.directConfig.ActSetItem;
import com.fingard.dsp.bank.directbank.FailCode;
import com.fingard.dsp.bank.directbank.PaymentState;
import com.fingard.dsp.bank.directbank.bankInterface.IRealTime;
import com.fingard.dsp.bank.reqrespobj.single.ReqQrySingle;
import com.fingard.dsp.bank.reqrespobj.single.ReqSingle;
import com.fingard.dsp.bank.reqrespobj.single.RetAtsSingle;
import com.fingard.dsp.bank.reqrespobj.single.detail.RetAtsSglDetail;
import com.fingard.io.FileHelper;
import com.fingard.text.StringHelper;
import com.fingard.xml.XmlTextReader;

public class GZELINK01RealTime extends GZELINK01Base implements IRealTime {
	public RetAtsSingle d_9108_RealTimeRec(ReqSingle p_req9108) throws Exception {
		RetAtsSingle retAts = new RetAtsSingle(p_req9108.reqHeader);
		RetAtsSglDetail tmpRetDetail = new RetAtsSglDetail();
		tmpRetDetail.reqSeqID = p_req9108.singleDetail.askNumber;
		
		try {
			ActSetItem actItem = getBankConfig().getActSetItem(p_req9108.singleDetail.recAct, "");
			if (actItem == null || !FileHelper.existFile(actItem.ownKeyStorePath)|| !FileHelper.existFile(actItem.oppCertFilePath)) {
				tmpRetDetail.respCode = "0";
				if(actItem == null){
					tmpRetDetail.respInfo = "未找到账号[" + p_req9108.singleDetail.recAct + "]批量商户配置信息";
				} else {
					tmpRetDetail.respInfo = "账号[" + p_req9108.singleDetail.recAct + "]证书文件不存在";
				}
				
				tmpRetDetail.transAmt = p_req9108.singleDetail.payAmount;
				tmpRetDetail.reqSeqID = p_req9108.singleDetail.askNumber;
				tmpRetDetail.transState = PaymentState.FAIL_Payment;
				tmpRetDetail.payInfoCode = FailCode.E9981;

				retAts.writeRetDetail(tmpRetDetail);
				return retAts;
			} else {
				GZELINK01Header bankHeader = new GZELINK01Header();
				
				bankHeader.transCode = "100004";
				
				String transCode = getBankConfig().getMapValueByKey("RecBusiCode", "0");
				if (StringHelper.hasAnyChar(transCode)) {
					bankHeader.busiCode = transCode;
				}
				
				bankHeader.reqSeqNo = p_req9108.singleDetail.askNumber;
				bankHeader.totalNum = "1";
				bankHeader.totalAmt = p_req9108.singleDetail.payAmount;
				
				StringBuilder reqMsg = new StringBuilder();
				reqMsg = writePayRecSubmitMsg(reqMsg, actItem, bankHeader);
				
				reqMsg.append("<TRANS_DETAIL>");
				
				reqMsg.append("<SN>0001</SN>");
				reqMsg.append("<E_USER_CODE></E_USER_CODE>");
				
				String bankCode = getBankConfig().getMapValueByKey("BankCodeMapping", p_req9108.singleDetail.payBankCode);
				reqMsg.append("<BANK_CODE>" + bankCode + "</BANK_CODE>");
				
				String cardType = p_req9108.singleDetail.cardType;
				if ("1".equals(cardType)) {
					reqMsg.append("<ACCOUNT_TYPE>01</ACCOUNT_TYPE>");
				} else if ("2".equals(cardType)) {
					reqMsg.append("<ACCOUNT_TYPE>00</ACCOUNT_TYPE>");
				}
				
				reqMsg.append("<ACCOUNT_NO>" + p_req9108.singleDetail.payAct + "</ACCOUNT_NO>");
				reqMsg.append("<ACCOUNT_NAME>" + p_req9108.singleDetail.payName + "</ACCOUNT_NAME>");
				reqMsg.append("<PROVINCE></PROVINCE>");
				reqMsg.append("<CITY></CITY>");
				reqMsg.append("<BANK_NAME></BANK_NAME>");
				
				String isPrivate = p_req9108.singleDetail.isPrivate;
				if ("1".equals(isPrivate)) {
					reqMsg.append("<ACCOUNT_PROP>0</ACCOUNT_PROP>");
				} else {
					reqMsg.append("<ACCOUNT_PROP>1</ACCOUNT_PROP>");
				}
				
				reqMsg.append("<AMOUNT>" + StringHelper.amountMultiply100(p_req9108.singleDetail.payAmount) + "</AMOUNT>");
				reqMsg.append("<CURRENCY>" + convertCurToBank(p_req9108.singleDetail.payCur) + "</CURRENCY>");
				reqMsg.append("<PROTOCOL></PROTOCOL>");
				reqMsg.append("<PROTOCOL_USERID></PROTOCOL_USERID>");
				reqMsg.append("<ID_TYPE></ID_TYPE>");
				reqMsg.append("<ID>" + p_req9108.singleDetail.certNum + "</ID>");
				reqMsg.append("<TEL>" + p_req9108.singleDetail.cellPhone + "</TEL>");
				reqMsg.append("<RECKON_ACCOUNT></RECKON_ACCOUNT>");
				reqMsg.append("<CUST_USERID></CUST_USERID>");
				reqMsg.append("<REMARK>" + p_req9108.singleDetail.memo + "</REMARK>");
                boolean useSingleReserve = getBankConfig().getValueAsBool("useSingleReserve");
                if (useSingleReserve) {
                    String reserve1 = getBankConfig().getMapValueByKey("reserveKeySingleMapping", "RESERVE1");
                    if (StringHelper.hasAnyChar(reserve1)) {
                        reserve1 = p_req9108.singleDetail.srcXElement.getSingleText(reserve1);
                    } else {
                        reserve1 = "";
                    }
                    reqMsg.append("<RESERVE1>" + reserve1 + "</RESERVE1>");

                    String reserve2 = getBankConfig().getMapValueByKey("reserveKeySingleMapping", "RESERVE2");
                    if (StringHelper.hasAnyChar(reserve1)) {
                        reserve2 = p_req9108.singleDetail.srcXElement.getSingleText(reserve2);
                    } else {
                        reserve2 = "";
                    }
                    reqMsg.append("<RESERVE2>" + reserve2 + "</RESERVE2>");

                    String reserve3 = getBankConfig().getMapValueByKey("reserveKeySingleMapping", "RESERVE3");
                    if (StringHelper.hasAnyChar(reserve3)) {
                        reserve3 = p_req9108.singleDetail.srcXElement.getSingleText(reserve3);
                    } else {
                        reserve3 = "";
                    }
                    reqMsg.append("<RESERVE3>" + reserve3 + "</RESERVE3>");

                    String reserve4 = getBankConfig().getMapValueByKey("reserveKeySingleMapping", "RESERVE4");
                    if (StringHelper.hasAnyChar(reserve4)) {
                        reserve4 = p_req9108.singleDetail.srcXElement.getSingleText(reserve4);
                    } else {
                        reserve4 = "";
                    }
                    reqMsg.append("<RESERVE4>" + reserve4 + "</RESERVE4>");
                } else {
                    reqMsg.append("<RESERVE1></RESERVE1>");
                    reqMsg.append("<RESERVE2></RESERVE2>");
                    reqMsg.append("<RESERVE3></RESERVE3>");
                    reqMsg.append("<RESERVE4></RESERVE4>");
                }
				reqMsg.append("<ELE_BANKNO></ELE_BANKNO>");
				reqMsg.append("<ABS></ABS>");
				reqMsg.append("<PS></PS>");
				reqMsg.append("<USE></USE>");
				reqMsg.append("<CRE_VAL_DATE></CRE_VAL_DATE>");
				reqMsg.append("<CRE_CVN2></CRE_CVN2>");
				reqMsg.append("<ACC_PASS></ACC_PASS>");
				reqMsg.append("</TRANS_DETAIL>");
				reqMsg.append("</TRANS_DETAILS>");
				reqMsg.append("</BODY>");
				reqMsg.append("</GZELINK>");
				
				// 签名
				String signData = reqMsg.toString().replaceAll("<SIGNED_MSG></SIGNED_MSG>", "");
				
				WriteBankLogLn2("签名原始数据:\r\n" + signData);
				
				String signature = signMsg(signData, actItem);
				
				// 请求数据
				String reqData = reqMsg.toString().replaceAll("<SIGNED_MSG></SIGNED_MSG>", "<SIGNED_MSG>" + signature + "</SIGNED_MSG>");
				WriteBankLogStep2(reqData);
				
				String[] tmpRetStr = sendDataToGZE(reqData, bankFront.getUrl("generalRecPay"));
				
				if(tmpRetStr[0].length() == 0) {
					WriteBankLogStep3(tmpRetStr[1]);
					
					StringBuilder tmpSbMsg = new StringBuilder();
					XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpRetStr[1], tmpSbMsg);
					
					if (tmpBkReader != null) {
						tmpRetDetail.respCode = "0";
						tmpRetDetail.respInfo = tmpBkReader.getFirstText("/GZELINK/INFO/ERR_MSG");
						
						String tmpRespCode = tmpBkReader.getFirstText("/GZELINK/INFO/RET_CODE");
						if ("0000".equals(tmpRespCode)) {
							tmpRetDetail.reqSeqID = tmpBkReader.getFirstText("/GZELINK/INFO/REQ_SN");
							
							String errMsg = tmpBkReader.getFirstText("/GZELINK/BODY/RET_DETAILS/RET_DETAIL/ERR_MSG");
							if (StringHelper.hasAnyChar(errMsg)) {
								tmpRetDetail.respInfo = errMsg;
							}
							
							String amount = tmpBkReader.getFirstText("/GZELINK/BODY/RET_DETAILS/RET_DETAIL/AMOUNT");
							if (StringHelper.hasAnyChar(amount)) {
								tmpRetDetail.transAmt = StringHelper.amountDivide100(amount);
							}
							
							tmpRetDetail.transState = StringHelper.joinNotEmpty("+", tmpRespCode, tmpBkReader.getFirstText("/GZELINK/BODY/RET_DETAILS/RET_DETAIL/RET_CODE"));
							tmpRetDetail.payInfoCode = tmpBkReader.getFirstText("/GZELINK/BODY/RET_DETAILS/RET_DETAIL/RET_CODE");
						} else {
							tmpRetDetail.transState = tmpRespCode;
							tmpRetDetail.payInfoCode = tmpRespCode;
						}
					} else {
						tmpRetDetail.respCode = "-1";
						tmpRetDetail.respInfo = tmpSbMsg.toString();
					}
				} else {
					tmpRetDetail.respCode = "-1"; 
					tmpRetDetail.respInfo = tmpRetStr[1];
				}
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			tmpRetDetail.respCode = "-1";
			tmpRetDetail.respInfo = ex.getMessage();
			WriteBankLogLn(ex);
		}
		
		retAts.writeRetDetail(tmpRetDetail);
		return retAts;
	}

	@Override
	public RetAtsSingle d_9144_QryRealTimeRec(ReqQrySingle p_req9144) throws Exception {
		RetAtsSingle retAts = new RetAtsSingle(p_req9144.reqHeader);
		RetAtsSglDetail tmpRetDetail = new RetAtsSglDetail();
		tmpRetDetail.reqSeqID = p_req9144.askNumber;
		
		try {
			ActSetItem actItem = getBankConfig().getActSetItem(p_req9144.recAct, "");
			if (actItem != null) {
				GZELINK01Header bankHeader = new GZELINK01Header();
				
				bankHeader.transCode = "200001";
				bankHeader.reqSeqNo = p_req9144.askNumber;
				
				StringBuilder reqMsg = new StringBuilder();
				reqMsg = writePayRecQueryMsg(reqMsg, actItem, bankHeader, p_req9144.reqHeader.transSeqID);
				
				String signData = reqMsg.toString().replaceAll("<SIGNED_MSG></SIGNED_MSG>", "");
				WriteBankLogLn2("待签名数据:\r\n" + signData);
				
				String signature = signMsg(signData, actItem);
				
				String reqData = reqMsg.toString().replaceAll("<SIGNED_MSG></SIGNED_MSG>", "<SIGNED_MSG>" + signature + "</SIGNED_MSG>");
				WriteBankLogStep2(reqData);
				
				String[] tmpRetStr = sendDataToGZE(reqData, bankFront.getUrl("generalRecPay"));
				if(tmpRetStr[0].length() == 0) {
					WriteBankLogStep3(tmpRetStr[1]);
					
					StringBuilder tmpSbMsg = new StringBuilder();
					XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpRetStr[1], tmpSbMsg);
					
					if (tmpBkReader != null) {
						tmpRetDetail.respCode = "0";
						tmpRetDetail.respInfo = tmpBkReader.getFirstText("/GZELINK/INFO/ERR_MSG");
						
						tmpRetDetail.reqSeqID = tmpBkReader.getFirstText("/GZELINK/BODY/QUERY_TRANS/QUERY_SN");
						if (StringHelper.isNullOrEmpty(tmpRetDetail.reqSeqID)) {
							tmpRetDetail.reqSeqID = p_req9144.askNumber;
						}
						
						String tmpRespCode = tmpBkReader.getFirstText("/GZELINK/INFO/RET_CODE");
						if (tmpRespCode.equals("0000")) {
							String amount = tmpBkReader.getFirstText("/GZELINK/BODY/RET_DETAILS/RET_DETAIL/AMOUNT");
							if (StringHelper.hasAnyChar(amount)) {
								tmpRetDetail.transAmt = StringHelper.amountDivide100(amount);
							}
							
							String tmpRetCode = tmpBkReader.getFirstText("/GZELINK/BODY/RET_DETAILS/RET_DETAIL/RET_CODE");
							String tmpErrMsg = tmpBkReader.getFirstText("/GZELINK/BODY/RET_DETAILS/RET_DETAIL/ERR_MSG");
							
							tmpRetDetail.transState = StringHelper.joinNotEmpty("+", tmpRespCode, tmpRetCode);
							tmpRetDetail.payInfoCode = tmpRetCode;
							
							if ("3999".equals(tmpRetCode)) {
								tmpRetDetail.payInfoCode = tmpErrMsg;
							}
							tmpRetDetail.respInfo = tmpErrMsg;
						} else {
							if ("3028".equals(tmpRespCode)) {
								tmpRetDetail.respCode = "-1";
							} else {
								tmpRetDetail.transState = tmpRespCode;
								tmpRetDetail.payInfoCode = tmpRespCode;
							}
						}
					} else {
						tmpRetDetail.respCode = "-1";
						tmpRetDetail.respInfo = tmpSbMsg.toString();
					}
				} else {
					tmpRetDetail.respCode = "-1"; 
					tmpRetDetail.respInfo = tmpRetStr[1];
				}
			} else {
				tmpRetDetail.respCode = "-1";
				tmpRetDetail.respInfo = "未找到账号:[" + p_req9144.recAct + "]商户配置信息!";
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			tmpRetDetail.respCode = "-1";
			tmpRetDetail.respInfo = ex.getMessage();
			WriteBankLogLn(ex);
		}
		
		retAts.writeRetDetail(tmpRetDetail);
		return retAts;
	}
}
